package com.example.demo.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import cn.com.jit.assp.ias.principal.UserPrincipal;
import cn.com.jit.assp.ias.sp.saml11.SPConst;
import cn.com.jit.assp.ias.sp.saml11.SPUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author guoyi
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/agent")
@Api(tags = "首页模块")
public class DemoController {

    private static final Log logger = LogFactory.getLog(DemoController.class);

    @GetMapping("/pki/token")
    @ApiOperation(value = "PKI系统跳转")
    public RedirectView pkiToken(HttpServletRequest request, @RequestParam @ApiParam("返回跳转Uri") String returnUri,
        RedirectAttributes redirectAttributes, HttpSession session) {
        UserPrincipal p = SPUtil.getUserPrincipal(request);
        boolean success = (p == null ? false : true);
        String idCard = null;
        log.info("PKI认证状态：{}", success);
        if (success) {
            String tokenId = (String)p.getAttribute(SPConst.KEY_SAML_ATTR_ID);
            log.info("令牌ID：{}", tokenId);
            String username = p.getName();
            String format = (String)p.getAttribute(SPConst.KEY_SAML_ATTR_SUBJECT_FORMAT);
            String issuer = (String)p.getAttribute(SPConst.KEY_SAML_ATTR_ISSUER);
            Date authn_instant = (Date)p.getAttribute(SPConst.KEY_SAML_ATTR_STATEMENT_AUTHN_INSTANT);
            Date instant = (Date)p.getAttribute(SPConst.KEY_SAML_ATTR_ISSUER_INSTANT);
            String method = (String)p.getAttribute(SPConst.KEY_SAML_ATTR_STATEMENT_AUTHN_MEHTOD);
            Date notBefore = (Date)p.getAttribute(SPConst.KEY_SAML_ATTR_NOT_BEFORE);
            Date notAfter = (Date)p.getAttribute(SPConst.KEY_SAML_ATTR_NOT_ON_OR_AFTER);
            String ip = (String)p.getAttribute(SPConst.KEY_SAML_ATTR_STATEMENT_AUTHN_CLIENT_IP);
            log.info("用户ID：{}，用户ID格式：{}，认证服务器：{}，认证结果签发时间：{}，登录时间：{}，认证方法：{}，认证结果起始有效期：{}，认证结果终止有效期：{}，用户IP地址：{}",
                username, format, issuer, instant, authn_instant, method, notBefore, notAfter, ip);
            if (!org.springframework.util.StringUtils.isEmpty(username)) {
                String[] array = username.split(",");
                if (array.length > 1) {
                    String[] cnArray = array[0].split("=");
                    if (cnArray.length == 2) {
                        String[] cnValueArray = cnArray[1].split(" ");
                        if (cnValueArray.length == 2) {
                            idCard = cnValueArray[1];
                        }
                    }
                }
            }
        } else {
            idCard = "获取PKI认证信息失败！";
        }
        RedirectView redirectTarget = new RedirectView();
        redirectTarget.setContextRelative(true);
        redirectTarget.setUrl(returnUri + "/#/Login?idCard=" + idCard);
        // redirectAttributes.addAttribute("idCard", idCard);
        return redirectTarget;
    }

    @PostMapping({"/oauth/idCard"})
    @ApiOperation(value = "PKI用户验证", notes = "传入租户ID:tenantId,身份证号:idCard")
    public Object token(@ApiParam(value = "租户ID", required = true) @RequestParam String tenantId,
        @ApiParam(value = "身份证号码", required = true) @RequestParam(required = false) String idCard) {
        // 根据身份证号码，进行授权认证，返回用户信息
        return null;
    }
}
